<?php

require_once 'Validate.php';
require_once 'Blogcomments.php';

class BlogcommentsHandler{
	
	private $db;
	private $validate;
	
	public function __construct(Database $db) {
			$this->db = $db;
			$this->validate = new Validate();
		}
	
	//Funktion för att skapa en kommentar.
	public function CreateBlogcomments($title, $comment, $blogpostid){
		
		$sqlQuery = "INSERT INTO blogcomments( title, comment, blogpostid) VALUES( ?, ?, ?)";
		
		$stmt = $this->db->Prepare($sqlQuery);
		
		$stmt->bind_param('ssi', $title, $comment, $blogpostid);
		
		if($this->db->Execute($stmt) === TRUE){
			return TRUE;
		}
			return FALSE;
	}
	
	//Funktion för att hämta alla kommentarer som tillhör ett specifikt blogginlägg.
	public function GetSpecificBlogComments($blogpostid){
		
		$sqlQuery = "SELECT blogcomments.id, blogcomments.title, blogcomments.comment, blogposts.title FROM blogcomments INNER JOIN blogposts ON blogposts.id = blogcomments.blogpostid WHERE blogpostid = ? ORDER BY id Desc";
		
		
		$stmt = $this->db->Prepare($sqlQuery);
						
		$stmt->bind_param('i', $blogpostid);
		
		$this->db->Execute($stmt);
		
		if ($stmt->bind_result($id, $title, $comment, $posttitle) == FALSE) {
            throw new \Exception($this->mysqli->error);
        }
		
        $ret = new BlogCommentArray();
        while ($stmt->fetch()) {
        	$ret->add(new Blogcomment($id, $title, $comment, $posttitle));
        }
                
        $stmt->close();
                
		//var_dump($ret);
                
        return $ret;
				
	}

	
	//Funktion för att ta bort en kommentar.
	public function DeleteBlogcomment($deleteCommentID){
		$sqlQuery = "DELETE FROM blogcomments WHERE id = ?";
		
		$stmt = $this->db->Prepare($sqlQuery);
		
		$stmt->bind_param('i', $deleteCommentID);
		
		if($this->db->execute($stmt)){
			$stmt->close();
			return true;
		}
		else
		{
			$stmt->close();
			return false;
		}		
	}
	//Kollar så att användaren har skrivit en titel.
	public function titleIsEmpty($title){
		if(empty($title)){
			return TRUE;
		}
		return FALSE;	
	}
	//Kollar så att användaren har skrivit en kommentar
	public function commentIsEmpty($comment){
		if(empty($comment)){
			return TRUE;
		}
		return FALSE;
	} 
	
	public function validateTitle($title){
		if($this->validate->Strings($title)){
			return true;
		}
		return false;
	}
	
	public function validateComment($comment){
		if($this->validate->Strings($comment)){
			return true;
		}
		return false;
	}
	
}
